package com.entrogy.controller;

import com.entrogy.bean.*;
import com.entrogy.service.ClassService;
import com.entrogy.service.StudentAttendanceService;
import com.entrogy.service.UserService;
import com.entrogy.utils.constants.ErrorEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @ClassName StudentAttendanceController
 * @Description
 * @Author luoxingjiang
 * @Date 2019/7/17 0017 上午 10:47
 * @Version 1.0
 **/
@RestController
@RequestMapping(value = "/studentAttendance")
@Api(description = "学生考勤接口")
public class StudentAttendanceController {


    @Autowired
    private StudentAttendanceService studentAttendanceService;

    @Autowired
    private UserService userService;

    @Autowired
    private ClassService classService;

    @GetMapping(value = "/getGradeList")
    @ApiOperation(value = "返回所有年级列表带早勤时间")
    public Msg getGradeList(){
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        List<GradeEntity> gradeList = studentAttendanceService.getGradeList(schoolCode);
        return Msg.success().add("gradeList", gradeList);
    }

    @PostMapping(value = "/addGradeAttendanceInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gradeId", value = "年级id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "gradeName", value = "年级名称", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "startTime", value = "早上开始考勤时间", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "endTime", value = "早上结束考勤时间", dataType = "String", paramType = "query", required = true),
    })
    @ApiOperation(value = "添加年级的早上考勤信息")
    public Msg addGradeAttendanceInfo(@ModelAttribute GradeAttendanceTimeEntity gradeAttendanceTime){
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        gradeAttendanceTime.setSchoolCode(schoolCode);
        boolean result = studentAttendanceService.addGradeAttendanceInfo(gradeAttendanceTime);
        if (result)
            return Msg.success();
        return Msg.fail(ErrorEnum.E_101, "添加失败！");
    }

    @PutMapping(value = "/updateGradeAttendanceInfo")
    @ApiOperation(value = "更新年级的早上考勤信息")
    public Msg updateGradeAttendanceInfo(@RequestBody List<GradeAttendanceTimeEntity> gradeAttendanceTime){
        boolean result = studentAttendanceService.updateGradeAttendanceInfo(gradeAttendanceTime);
        if (result)
            return Msg.success();
        return Msg.fail(ErrorEnum.E_101, "设置失败！");
    }

    @GetMapping(value = "/listClassAttendanceOverView")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "time", value = "查询时间", dataType = "Date", paramType = "query", required = true),
            @ApiImplicitParam(name = "timeFrameType", value = "查询的时段，1为早上，2为中午，3为下午", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "classId", value = "查询的班级id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "gradeId", value = "查询的年级id", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "返回班级的考勤信息概览")
    public Msg listClassAttendanceOverView(String uid, @DateTimeFormat(pattern = "yyyy-MM-dd") Date time, Integer timeFrameType, Integer classId, Integer gradeId){
        // 多职位切换备份
//        boolean isClassLeader = userService.isClassLeader(uid);
        // ************************新版本不做权限判定，直接查询所有班级出来显示即可**************************
//        boolean isClassLeader = positionService.checkPosition(uid, 16);
//        Set<Integer> classIds = new HashSet<>();
//        // 如果该用户是班主任
//        if (isClassLeader){
//            // 查询班主任所带的班级id并存起来
//            classIds.addAll(classService.listClassLeaderManagementClassId(uid));
//        }
//        // 如果该用户是年级主任
////        boolean isGradeLeader = userService.isGradeLeader(uid);
//        boolean isGradeLeader = positionService.checkPosition(uid, 15);
//        if (isGradeLeader){
//            // 查询年级主任所带的班级id并存起来
//            classIds.addAll(classService.listGradeLeaderManagementClassId(uid));
//        }
//        if (!isClassLeader && !isGradeLeader){
//            return Msg.fail(ErrorEnum.E_101, "对不起，您没有权限！");
//        }
        Integer schoolCode = userService.getSchoolCodeByUserId(uid);
        List<Integer> classIds = new ArrayList<>();
        if (classId != null){
            classIds.add(classId);
        }else {
            classIds = classService.listClassIdBySchoolCode(schoolCode, gradeId);
        }
        // 返回某些班级的考勤时间概览
        return Msg.success().add("classAttendanceOverViewList", listClassAttendanceOverview(timeFrameType, time, schoolCode, classIds));
    }

    @GetMapping(value = "/listGradeAttendanceOverView")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "time", value = "查询时间", dataType = "Date", paramType = "query", required = true),
            @ApiImplicitParam(name = "timeFrameType", value = "查询的时段，1为早上，2为中午，3为下午", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "gradeId", value = "查询的年级id", dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "返回年级的考勤信息概览")
    public Msg listGradeAttendanceOverView(String uid, @DateTimeFormat(pattern = "yyyy-MM-dd") Date time, Integer timeFrameType, Integer gradeId){
        Integer schoolCode = userService.getSchoolCodeByUserId(uid);
        List<Integer> classIds = classService.listClassIdBySchoolCode(schoolCode, gradeId);
        // 返回某些年级的考勤时间概览
        List<ClassAttendanceEntity> classAttendanceOverViewList = listClassAttendanceOverview(timeFrameType, time, schoolCode, classIds);
        // 定义一个map用于统计根据班级考勤情况来统计年级考勤情况
        Map<Integer, GradeAttendanceEntity> gradeAttendanceMap = new HashMap<>();
        for (ClassAttendanceEntity classAttendanceEntity : classAttendanceOverViewList) {
            GradeAttendanceEntity gradeAttendance = new GradeAttendanceEntity();
            gradeAttendance.setGradeId(classAttendanceEntity.getGradeId())
                    .setTotalStudentCount(0)
                    .setShouldAttendance(0)
                    .setLateStudentCount(0)
                    .setAskForLeaveStudentCount(0)
                    .setActualAttendance(0)
                    .setGradeName(classAttendanceEntity.getClassName().substring(0, 6))
                    .setNoAttendanceCount(0);
            gradeAttendanceMap.put(classAttendanceEntity.getGradeId(), gradeAttendance);
        }
        gradeAttendanceMap.forEach((k,v) -> {
            for (ClassAttendanceEntity classAttendanceEntity : classAttendanceOverViewList) {
                if (k.equals(classAttendanceEntity.getGradeId())){
                    v.setActualAttendance(classAttendanceEntity.getActualAttendance() == null ? null : v.getActualAttendance() + classAttendanceEntity.getActualAttendance());
                    v.setAskForLeaveStudentCount(v.getAskForLeaveStudentCount() + classAttendanceEntity.getAskForLeaveStudentCount());
                    v.setLateStudentCount(classAttendanceEntity.getLateStudentCount() == null ? null : v.getLateStudentCount() + classAttendanceEntity.getLateStudentCount());
                    v.setShouldAttendance(v.getShouldAttendance() + classAttendanceEntity.getShouldAttendance());
                    v.setTotalStudentCount(v.getTotalStudentCount() + classAttendanceEntity.getTotalStudentCount());
                    v.setNoAttendanceCount(classAttendanceEntity.getNoAttendanceCount() == null ? null : v.getNoAttendanceCount() + classAttendanceEntity.getNoAttendanceCount());
                }
            }
        });
        return Msg.success().add("gradeAttendanceMap", gradeAttendanceMap);
    }

//    @GetMapping(value = "/listSchoolAttendanceOverView")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Integer", paramType = "query", required = true),
//            @ApiImplicitParam(name = "time", value = "查询时间", dataType = "Date", paramType = "query", required = true),
//            @ApiImplicitParam(name = "timeFrameType", value = "查询的时段，1为早上，2为中午，3为下午", dataType = "Integer", paramType = "query", required = true),
//            @ApiImplicitParam(name = "gradeId", value = "查询的年级id", dataType = "Integer", paramType = "query"),
//    })
//    @ApiOperation(value = "返回学校的考勤信息概览")
//    public Msg listSchoolAttendanceOverView(String uid, @DateTimeFormat(pattern = "yyyy-MM-dd") Date time, Integer timeFrameType){
//        Integer schoolCode = userService.getSchoolCodeByUserId(uid);
//        List<Integer> classIds = classService.listClassIdBySchoolCode(schoolCode, null);
//        // 返回某些班级的考勤时间概览
//        List<ClassAttendanceEntity> classAttendanceOverViewList = listClassAttendanceOverview(timeFrameType, time, schoolCode, classIds);
//        SchoolAttendanceEntity schoolAttendance = new SchoolAttendanceEntity();
//        schoolAttendance.setSchoolCode(schoolCode)
//                .setTotalStudentCount(0).setShouldAttendance(0).setLateStudentCount(0)
//                .setAskForLeaveStudentCount(0).setActualAttendance(0);
//        for (ClassAttendanceEntity classAttendanceEntity : classAttendanceOverViewList) {
//
//        }
//        return Msg.success().add("schoolAttendance", schoolAttendance);
//    }



    @GetMapping(value = "/getClassAttendanceDetailInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "time", value = "查询时间", dataType = "Date", paramType = "query", required = true),
            @ApiImplicitParam(name = "classId", value = "查询的班级id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "gradeId", value = "查询的年级id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "timeFrameType", value = "查询的时段，1为早上，2为中午，3为下午", dataType = "Integer", paramType = "query", required = true),
    })
    @ApiOperation(value = "返回当前时段班级的考勤详细信息，包括该时段的迟到学生名单以及当天的请假学生名单，以及迟到学生的通行记录")
    public Msg getClassAttendanceDetailInfo(String uid, @DateTimeFormat(pattern = "yyyy-MM-dd") Date time, Integer timeFrameType, Integer classId, Integer gradeId){
        Integer schoolCode = userService.getSchoolCodeByUserId(uid);
        Map<String, Object> classAttendanceDetailInfo;
        if(timeFrameType == 1){
            // 返回早上考勤统计详情
            classAttendanceDetailInfo = studentAttendanceService.getMorningAttendanceDetailInfo(classId, time, schoolCode, gradeId);
            return Msg.success().add("classAttendanceDetailInfo", classAttendanceDetailInfo);
        }else if (timeFrameType == 2 || timeFrameType == 3){
            // 返回中午或者下午的考勤统计详情
            classAttendanceDetailInfo = studentAttendanceService.getNoonOrAfternoonAttendanceDetailInfo(classId, time, schoolCode, timeFrameType, gradeId);
            return Msg.success().add("classAttendanceDetailInfo", classAttendanceDetailInfo);
        }
        return Msg.fail(ErrorEnum.E_90003, ErrorEnum.E_90003.getErrorMsg());
    }

//    @GetMapping(value = "/grade-attendance-detail-info")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Integer", paramType = "query", required = true),
//            @ApiImplicitParam(name = "time", value = "查询时间", dataType = "Date", paramType = "query", required = true),
//            @ApiImplicitParam(name = "gradeId", value = "查询班级id", dataType = "Integer", paramType = "query", required = true),
//            @ApiImplicitParam(name = "timeFrameType", value = "查询的时段，1为早上，2为中午，3为下午", dataType = "Integer", paramType = "query", required = true),
//    })
//    @ApiOperation(value = "返回当前时段班级的考勤详细信息，包括该时段的迟到学生名单以及当天的请假学生名单，以及迟到学生的通行记录")
//    public Msg getGradeAttendanceDetailInfo(String uid, @DateTimeFormat(pattern = "yyyy-MM-dd") Date time, Integer timeFrameType, Integer gradeId){
//        Integer schoolCode = userService.getSchoolCodeByUserId(uid);
//        Map<String, Object> classAttendanceDetailInfo;
//        if(timeFrameType == 1){
//            // 返回早上考勤统计详情
//            classAttendanceDetailInfo = studentAttendanceService.getMorningAttendanceDetailInfo(classId, time, schoolCode);
//            return Msg.success().add("classAttendanceDetailInfo", classAttendanceDetailInfo);
//        }else if (timeFrameType == 2 || timeFrameType == 3){
//            // 返回中午或者下午的考勤统计详情
//            classAttendanceDetailInfo = studentAttendanceService.getNoonOrAfternoonAttendanceDetailInfo(classId, time, schoolCode, timeFrameType);
//            return Msg.success().add("classAttendanceDetailInfo", classAttendanceDetailInfo);
//        }
//        return Msg.fail(ErrorEnum.E_90003, ErrorEnum.E_90003.getErrorMsg());
//    }


    /**
     * 返回某些班级的考勤概览
     * @param timeFrameType
     * @param time
     * @param schoolCode
     * @param classIds
     * @return
     */
    private List<ClassAttendanceEntity> listClassAttendanceOverview(Integer timeFrameType, Date time, Integer schoolCode, List<Integer> classIds){
        List<ClassAttendanceEntity> classAttendanceOverViewList;
        if(timeFrameType == 1){
            // 返回早上考勤统计
            classAttendanceOverViewList = studentAttendanceService.listClassMorningAttendanceInfo(classIds, time, schoolCode);
            return classAttendanceOverViewList;
        }else if (timeFrameType == 2 || timeFrameType == 3){
            // 返回中午或者下午的考勤统计
            classAttendanceOverViewList = studentAttendanceService.listClassNoonOrAfternoonAttendanceInfo(classIds, time, schoolCode, timeFrameType);
            return classAttendanceOverViewList;
        }else {
            return null;
        }
    }


}
